package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.messageprocessors.RequestProcessorImp;

import java.util.Date;

import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.AddressType;
import net.wimpi.modbus.Modbus;
import net.wimpi.modbus.msg.ExceptionResponse;
import net.wimpi.modbus.msg.ModbusRequest;
import net.wimpi.modbus.msg.ModbusResponse;
import net.wimpi.modbus.msg.ModbusUtil;
import net.wimpi.modbus.msg.WriteSingleRegisterRequest;
import net.wimpi.modbus.msg.WriteSingleRegisterResponse;
import net.wimpi.modbus.procimg.IllegalAddressException;
import net.wimpi.modbus.procimg.Register;

public class WriteSingleRegisterRequestProcessor extends
		AbstractRequestProcessor {

	@Override
	public ModbusResponse processRequest(ModbusRequest req) {
		
		ModbusResponse res;
		//TODO: chequear limites del protocolo
		Register reg = ((WriteSingleRegisterRequest) req).getRegister();
		int ref = ((WriteSingleRegisterRequest) req).getReference();
		Date date = new Date();
		
		res = new WriteSingleRegisterResponse(ref, reg.getValue());
		
		try {

			getImage().setRegister(ref,reg,date);
			
			if( getDeciveDAO() != null )
					getDeciveDAO().saveValue( getDevice(), ref , reg.getValue() , AddressType.HOLDING_REGISTER );
			ModbusUtil.setFunctionCode(res, Modbus.WRITE_MULTIPLE_REGISTERS);
		}
		catch(IllegalAddressException e){
			res = new ExceptionResponse(req.getFunctionCode(), 2);
		}
		
		ModbusUtil.setMessageData(res,req);
		return res;
	}

}
